<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2016/11/28
 * Time: 13:47
 * 对于输入信息没有提交的 自动来提交支付信息
 */

date_default_timezone_set('PRC');
define('ENV', 'test');
define('LANG', 'HK');//國家代碼
define('API_HOST1', 'http://wru8zys.zwbpay.com/payment/interface/do');
define('API_HOST2', 'http://wru8zys.gtopay.com/payment/interface/do');
define('SERVER_ROOT', 'http://www.linchpin-shop.com/');
switch (ENV) {
    case 'dev':
        define('SERVER', '127.0.0.1');
        define('PORT', '3307');
        define('DBNAME', 'jhdb');
        define('DBUSER', 'root');
        define('PWD', 'usbw');
        break;
    case 'test':
        define('SERVER', '127.0.0.1');
        define('PORT', '3306');
        define('DBNAME', 'jhdb');
        define('DBUSER', 'root');
        define('PWD', 'jh!@#2016');
        break;
    case 'prod':
        define('SERVER', '127.0.0.1');
        define('PORT', '3306');
        define('DBNAME', 'jhdb');
        define('DBUSER', 'root');
        define('PWD', 'jh!@#2016');
        break;
    default:
        break;
}


//脚本读取数据库
function getAllNoSumitPayInfos()
{
    $dsn = 'mysql:dbname=' . DBNAME . ';host=' . SERVER . ';port=' . PORT;
    $dbh = new PDO($dsn, DBUSER, PWD);
    $dbh->query("set names utf8");
    $sql = "select * from payment_log where RetCode = '' and RetStatus = '' and RetMsg = ''";
//    $sql = "select * from payment_log where OrderID = 'SN_1096'";
    $sth = $dbh->query($sql);
    $results = $sth->fetchAll(PDO::FETCH_ASSOC);
    return $results;
}


function getPayConfig($site)
{
    $dsn = 'mysql:dbname=' . DBNAME . ';host=' . SERVER . ';port=' . PORT;
    $dbh = new PDO($dsn, DBUSER, PWD);
    $dbh->query("set names utf8");
    $sql = "select * from pay_configuration where app_site='$site' limit 1";
    $sth = $dbh->query($sql);
    $row = $sth->fetch();
    return $row;
}


function getOrdersBySn($sn)
{
    $dsn = 'mysql:dbname=' . DBNAME . ';host=' . SERVER . ';port=' . PORT;
    $dbh = new PDO($dsn, DBUSER, PWD);
    $dbh->query("set names utf8");
    $sql = "select * from jh_order_sn_record where order_sn='$sn'";
    $sth = $dbh->query($sql);
    $row = $sth->fetch();
    return $row;
}


function createLog($content, $file = '')
{
    if (!$file) {
        $logfile = dirname(__FILE__) . '/logs/debuglog' . date('Ymd') . '.txt';
    } else {
        $logfile = $file;
    }

    if (!file_exists(dirname($logfile))) {
        @mkdir(dirname($logfile), 0777, true);
    }
    error_log(date("[Y-m-d H:i:s]") . " -[" . $_SERVER['REQUEST_URI'] . "] :" . $content . "\n", 3, $logfile);
}

function getMsgByCode($code)
{
    $array = array(1001 => "表單參數缺少", 1002 => "郵箱格式錯誤", 1003 => "IP地址錯誤", 1004 => "信用卡號錯誤", 1005 => "商戶號不存在", 1006 => "網址不存在", 1007 => "卡種不存在", 1008 => "簽名數據錯誤", 1009 => "貨幣代碼錯誤", 1010 => "國家代碼錯誤", 1012 => "同一卡號或郵箱，24小時內交易超限", 2001 => "系統故障");
    if (!$array[$code]) {
        return "支付错误";
    }
    return $array[$code];
}


$payRecords = getAllNoSumitPayInfos();
foreach ($payRecords as $pay) {
    if (!$pay['CardNumber']) {
        continue;
    }
    sumitPayToApi($pay);
}


function updatePayInfo($sn, $data)
{
    $dsn = 'mysql:dbname=' . DBNAME . ';host=' . SERVER . ';port=' . PORT;
    $dbh = new PDO($dsn, DBUSER, PWD);
    $dbh->query("set names utf8");
    $str = "";
    $sign = ",";
    $i = 0;
    foreach ($data as $k => $v) {
        $i++;
        if ($i == count($data)) {
            $sign = "";
        }
        $str .= "`" . $k . "`" . "=" . "'$v'" . $sign;
    }
    $sql = "UPDATE `payment_log` SET $str WHERE `OrderID` = '$sn'";
    createLog("update payInfo->" . $sql);
    $ret = $dbh->exec($sql);
    return $ret;
}


function saveEmailData($data)
{

    try {
        $dsn = 'mysql:dbname=' . DBNAME . ';host=' . SERVER . ';port=' . PORT;
        $dbh = new PDO($dsn, DBUSER, PWD);
        $dbh->query("set names utf8");

        $product_id = $data['products_info'];
        $product_id = "'$product_id'";

        $order_sn = $data['order_sn'];
        $order_sn = "'$order_sn'";

        $to_email = $data['to_email'];
        $to_email = "'$to_email'";

        if (isset($data['createtime'])) {
            $createtime = $data['createtime'];
            $modifytime = time();
            $sql = "replace into yiye_mailinfo(`products_info`,`order_sn`,`to_email`,`createtime`,`modifytime`) values ($product_id,$order_sn,$to_email,$createtime,$modifytime)";
        } else {
            $modifytime = time();
            $sql = "replace into yiye_mailinfo(`products_info`,`order_sn`,`to_email`,`modifytime`) values ($product_id,$order_sn,$to_email,$modifytime)";
        }


        $res = $dbh->exec($sql);
        return $res;

    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}

function sumitPayToApi($payInfo)
{

    createLog(var_export($payInfo, true));
    $payConfig = getPayConfig($payInfo['URL']);
    $order = getOrdersBySn($payInfo['OrderID']);

    $data['CardNumber'] = $payInfo['CardNumber'];
    $data['CardMonth'] = $payInfo['CardMonth'];
    $data['CardYear'] = $payInfo['CardYear'];
    $data['CardCvv'] = $payInfo['CardCvv'];


    $data['MerchantID'] = trim($payInfo['MerchantID']);
    $data['TransNo'] = trim($payInfo['TransNo']);
    $data['OrderID'] = trim($payInfo['OrderID']);
    $data['Currency'] = trim($payInfo['Currency']);
    $data['Amount'] = trim($payInfo['Amount']);
    $data['MD5info'] = strtoupper(md5(trim($payConfig['app_key']) . trim($payConfig['merchant_id']) . trim($payConfig['tran_num']) . trim($payInfo['OrderID']) . trim($payInfo['Currency']) . trim($payInfo['Amount'])));
    $data['Version'] = 'V4.5';


    $data['BName'] = $payInfo['BName'];
    $data['BEmail'] = $payInfo['BEmail'];
    $data['BAddress'] = $payInfo['BAddress'];

    if (LANG == 'HK') {
        $data['BCity'] = "香港";
    } else {
        $data['BCity'] = "台灣";
    }

    $data['BCountry'] = LANG;
    $data['BState'] = "";

    $data['BPostcode'] = $payInfo['BPostcode'];
    $data['BPhone'] = $payInfo['BPhone'];


    $data['DName'] = $order['user_name'];
    $data['DEmail'] = $order['email'];
    $data['DAddress'] = $order['addres'];

    if (LANG == 'HK') {
        $data['DCity'] = "香港";
    } else {
        $data['DCity'] = "台灣";
    }

    $data['DCountry'] = LANG;
    $data['DState'] = "";

    $data['DPostcode'] = $order['post_code'];
    $data['DPhone'] = $order['phone'];


    $data['URL'] = $payInfo['URL'];
    $data['IP'] = $payInfo['IP'];
    $data['UserAgent'] = $payInfo['UserAgent'];
    $data['AcceptLanguage'] = $payInfo['AcceptLanguage'];

    $data['Products'] = $payInfo['Products'];


    createLog(var_export($data, true));

    if ($payConfig['api_url1']) {
        $api_url1 = $payConfig['api_url1'];
    } else {
        $api_url1 = API_HOST1;
    }
    if ($payConfig['api_url2']) {
        $api_url2 = $payConfig['api_url2'];
    } else {
        $api_url2 = API_HOST2;
    }

    createLog($api_url1);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $result = curl_exec($ch);
    curl_close($ch);
    if (!$result) {
        curl_setopt($ch, CURLOPT_URL, $api_url2);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        if (!$result) {
            $url = SERVER_ROOT . 'failed.php?msg=' . getMsgByCode(2001) . '&order_sn=' . $payInfo['OrderID'];
            exit(json_encode(array("code" => -1, "url" => $url)));
        }
    }
    createLog($result);
    $result = json_decode($result, true);

    $pay_info = array("OrderID" => $data['OrderID'], "MerchantID" => $data['MerchantID'], "TransNo" => $data['TransNo'], "Currency" => $data['Currency'], "Amount" => $data['Amount'], "Version" => $data['Version'],
        "BName" => $data['BName'], "BEmail" => $data['BEmail'], "BAddress" => $data['BAddress'], "BCity" => $data['BCity'], "BState" => $data['BState'], "BPostcode" => $data['BPostcode'], "BCountry" => $data['BCountry'], "BPhone" => $data['BPhone'],
        "CardNumber" => $data['CardNumber'], "CardMonth" => $data['CardMonth'], "CardYear" => $data['CardYear'], "CardCvv" => $data['CardCvv'], "URL" => $data['URL'], "IP" => $data['IP'], "UserAgent" => $data['UserAgent'], "AcceptLanguage" => $data['AcceptLanguage'],
        "Products" => $data['Products'], "RetCode" => "", "RetStatus" => "", "RetMsg" => "", "createtime" => time(), "modifytime" => time());
//    logPayInfo($pay_info);//再次支付，只需要更新数据就行
    createLog("logUserInfo->" . var_export($pay_info, true), dirname(__FILE__) . '/logs/paylogs.txt');


    if ($result['error'] == true) {
        $patterns = '/\d+/'; //第一种
        preg_match_all($patterns, $result['code'], $ret_arr);
        $msg = getMsgByCode($ret_arr[0][0]);
        $url = SERVER_ROOT . 'failed.php?msg=' . $msg . '&order_sn=' . $payInfo['OrderID'];
        $ret = array("code" => $ret_arr[0][0], "url" => $url);
        updatePayInfo($payInfo['OrderID'], array("RetCode" => $ret_arr[0][0], "RetMsg" => $msg, "RetStatus" => "", "modifytime" => time()));
    } else {
        if ($result['order']['Status'] == 1) {
            $OrderID = $result['order']['OrderID'];
            $Currency = $result['order']['Currency'];
            $Amount = $result['order']['Amount'];
            $Code = $result['order']['Code'];
            $Status = $result['order']['Status'];
            $MD5info = $result['order']['MD5info'];

            $MD5src = trim($payConfig['app_key']) . trim($payConfig['tran_num']) . trim($OrderID) . trim($Currency) . trim($Amount) . trim($Code) . trim($Status);
            $MD5sign = strtoupper(md5($MD5src));
            if ($MD5sign == $MD5info) {
                //跳轉到支付成功頁面
                $url = SERVER_ROOT . 'success.php?order_sn=' . $result['order']['OrderID'];
                $ret = array("code" => 0, "url" => $url);

                updatePayInfo($result['order']['OrderID'], array("RetCode" => $result['order']['Code'], "RetMsg" => "支付成功", "RetStatus" => $result['order']['Status'], "modifytime" => time()));
                $mail_data = array("to_email" => (isset($data['DEmail']) ? $data['DEmail'] : $data['BEmail']), "order_sn" => $result['order']['OrderID'], "products_info" => $data['Products'], "createtime" => time());
                saveEmailData($mail_data);
            } else {
                //否則跳轉到失敗頁面，提示重新支付
                $msg = '返回值簽名解析錯誤';
                $url = SERVER_ROOT . 'failed.php?msg=' . $msg . '&order_sn=' . $result['order']['OrderID'];
                updatePayInfo($result['order']['OrderID'], array("RetCode" => $result['order']['Code'], "RetMsg" => $msg, "RetStatus" => $result['order']['Status'], "modifytime" => time()));

            }
        } elseif ($result['order']['Status'] == 4) {
            $msg = '正在處理中';
            $url = SERVER_ROOT . 'failed.php?msg=' . $msg . '&order_sn=' . $result['order']['OrderID'];
            $ret = array("code" => $result['order']['Code'], "url" => $url);
            updatePayInfo($result['order']['OrderID'], array("RetCode" => "", "RetMsg" => $msg, "RetStatus" => $result['order']['Status'], "modifytime" => time()));
        } else {//有錯誤
            $msg = '支付失敗';
            $url = SERVER_ROOT . 'failed.php?msg=' . $msg . '&order_sn=' . $result['order']['OrderID'];
            $ret = array("code" => $result['order']['Code'], "url" => $url);
            updatePayInfo($result['order']['OrderID'], array("RetCode" => "", "RetMsg" => $msg, "RetStatus" => $result['order']['Status'], "modifytime" => time()));
            //測試發郵件
//        $mail_data = array("to_email" => (isset($data['DEmail']) ? $data['DEmail'] : $data['BEmail']), "order_sn" => $result['order']['OrderID'], "products_info" => $productsInfo, "createtime" => time());
//        Utils::createLog(var_export($mail_data, true));
//        saveEmailData($mail_data);
        }
    }
}
